package com.example.zsf.activity;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.example.zsf.R;
import com.example.zsf.base.ZSFClearFocus;
import com.example.zsf.base.ZSFInputBaseActivity;
import com.example.zsf.fragment.MessageFragment;
import com.example.zsf.fragment.MineFragment;
import com.example.zsf.fragment.MobileFragment;
import com.example.zsf.fragment.PCFragment;
import com.example.zsf.message.NotificationEventMessage;
import com.example.zsf.model.TabModel;
import com.example.zsf.view.BottomBar;
import com.example.zsf.view.BottomBarTab;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends ZSFInputBaseActivity {

    @BindView(R.id.bottomBar)
    BottomBar bottomBar;

    private List<Fragment> fragments;
    private int currentFragment;
    private boolean needSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initUI();
        initData();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        needSwitch = intent.getBooleanExtra("switch",false);
        if (needSwitch){
            bottomBar.setCurrentItem(2);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveNotification(NotificationEventMessage eventMessage){
        if (isForeground(this, getClass().getName())){
            bottomBar.setCurrentItem(2);
        }
    }

    private boolean isForeground(Context context, String className){
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }



    private void initUI() {
        Window window = getWindow();
        View decorView = window.getDecorView();
        int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        decorView.setSystemUiVisibility(option);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void clearFocus() {
        super.clearFocus();
        for (Fragment f : fragments) {
            if (f instanceof ZSFClearFocus) {
                ((ZSFClearFocus) f).clearFocus();
            }
        }
    }

    private void initData() {
        fragments = new ArrayList<>();
        fragments.add(new MobileFragment());
        fragments.add(new PCFragment());
        fragments.add(new MessageFragment());
        fragments.add(new MineFragment());
        List<TabModel> tabModelList = new ArrayList<>();
        tabModelList.add(new TabModel("手机端", R.mipmap.mobile, R.mipmap.mobile_selected));
        tabModelList.add(new TabModel("电脑端", R.mipmap.pc, R.mipmap.pc_selected));
        tabModelList.add(new TabModel("消息", R.mipmap.message, R.mipmap.message_selected));
        tabModelList.add(new TabModel("我的", R.mipmap.mine, R.mipmap.mine_selected));
        setFragmentTabs(tabModelList);
        addFragment(currentFragment);
        bottomBar.getItem(currentFragment).setSelected(true);
        if (needSwitch) {
            bottomBar.setCurrentItem(2);
        }
    }

    private void setFragmentTabs(List<TabModel> beanList) {
        for (int i = 0; i < beanList.size(); i++) {
            bottomBar
                    .addItem(new BottomBarTab(this, beanList.get(i)));
        }
        bottomBar.setOnTabSelectedListener(new BottomBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                addFragment(position);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });
    }

    private void addFragment(int temp) {
        Fragment fragment = fragments.get(temp);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        fragments.get(currentFragment).onPause(); // 暂停当前tab
        fragments.get(currentFragment).onStop(); // 暂停当前tab
        currentFragment = temp; // 更新目标tab为当前tab
        if (fragment.isAdded()) {
            fragment.onStart(); // 启动目标tab的onStart()
            fragment.onResume(); // 启动目标tab的onResume()
        } else {
            ft.add(R.id.myfragment, fragment);
        }
        showTab(temp); // 显示目标tab
        ft.commit();
    }

    /**
     * 切换tab
     */
    private void showTab(int idx) {
        for (int i = 0; i < fragments.size(); i++) {
            Fragment fragment = fragments.get(i);
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            if (idx == i) {
                ft.show(fragment);
            } else {
                ft.hide(fragment);
            }
            ft.commitAllowingStateLoss();
        }
    }
}